from flask import render_template,redirect,url_for,session, flash
from flask_login import login_required, current_user
#from flaskext.uploads import UploadSet, IMAGES
from bson.dbref import DBRef
from model.category import CategoryDao
from service.category import CategoryService, CategoryForm
from controller import app
import json

IMAGES = tuple('jpg jpe jpeg png gif svg bmp'.split())



@app.route('/manage_categories')
@app.route('/manage_categories', methods=['GET','POST'])
@login_required
def manage_categories():
    form = CategoryForm()
    if form.is_submitted():
        if form.has_error():
            session['errors_json'] = json.dumps(form.errors)
            return redirect(url_for('display_categories'))#errors_json=json.dumps(form.errors)))
        else:
            service = CategoryService()
            service.submit_category(form)
            
            #flash("Image saved.")
            #return redirect(url_for('pictures'))
            return redirect(url_for('display_categories'))
    return redirect(url_for('display_categories'))

@app.route('/display_categories')
@login_required
def display_categories():
    service = CategoryService()
    cats = service.get_categories()
    if len(cats) == 0:
        return render_template("manage_categories.html", _categories=None)
    else:
        return render_template("manage_categories.html", categories=cats)
    '''
    category_dao = CategoryDao()
    _categories = category_dao.all()
    if len(_categories) == 0:
        return render_template("manage_categories.html", _categories=None)
    else:
        cats = []
        for _category in _categories:
            if _category.parent is not None:
                parent = category_dao.find_one({'_id':_category.parent.id})
                cats.append({"name":_category.name, "description":_category.description, "parent":parent.name})
            else:
                cats.append({"name":_category.name, "description":_category.description, "parent":"None"})
        
        return render_template("manage_categories.html", categories=cats)
    '''
@app.route("/delete_categories", methods=["GET", "POST"])
@login_required
def delete_categories():
    
    category_dao = CategoryDao()
    '''
    form = CategoriesForm()
    ids = form.request.form.getlist('selected')
    for _id in ids:
        category = category_dao.filter_first(id=int(_id))
        category_dao.remove_from_db(category)
    ''' 
    return render_template("manage_categories.html", categories=category_dao.all())            
